import { asyncRoutes } from '@/router'
import router from '@/router'
import store from './store'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import getPageTitle from '@/utils/get-page-title'

const whiteList = ['/login', '/404']
router.beforeEach(async(to, from, next) => {
  // 动态设置网页标题
  document.title = getPageTitle(to.meta.title)
  NProgress.start()
  if (store.state.user.token) {
    if (to.path === '/login') {
      // console.log('小伙子，不要吃回头草')
      next('/')
      NProgress.done()
    } else {
      // 第一次进主页之前，获取用户的信息
      if (!store.state.user.userInfo.id) {
        const menu = await store.dispatch('user/getUserInfo')
        console.log('asyncRoutes', asyncRoutes)
        console.log('menu', menu)
        const filterRoutes = asyncRoutes.filter(item => {
          const routeName = item.children[0].name
          // console.log(routeName)
          return menu.includes(routeName)
        })
        // 动态添加404路由
        // console.log(filterRoutes, 'oldfilterRoutes')
        filterRoutes.push({ path: '*', redirect: '/404', hidden: true })
        // console.log(filterRoutes, 'newfilterRoutes')
        // 将动态路由保存到vuex,渲染左侧菜单
        store.commit('menu/setMenusList', filterRoutes)
        // 动态添加路由
        router.addRoutes(filterRoutes)
        // 解决刷新出现的白屏bug：保证动态路由添加完成，页面渲染完成再跳转页面
        next({
          ...to, // next({ ...to })的目的,是保证路由添加完了再进入页面 (可以理解为重进一次)
          replace: true // 重进一次, 不保留重复历史
        })
      } else {
        next()
      }
    }
  } else {
    // console.log(router, 'router852852852')
    if (whiteList.includes(to.path)) {
      next()
    } else {
      // console.log('小伙子，你没资格')
      next('/login')
      // console.log('跳转之后走这个代码')
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})
